package com.zqxx.examine.portal.controller.action;

import java.util.List;

import javax.servlet.http.HttpServletRequest;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import com.zqxx.examine.common.utils.Page;
import com.zqxx.examine.model.exam.Message;
import com.zqxx.examine.model.question.Comment;
import com.zqxx.examine.model.question.Comments;
import com.zqxx.examine.portal.security.UserInfo;
import com.zqxx.examine.portal.service.CommentService;

@Controller
public class CommentAction
{
  @Autowired
  private CommentService commentService;
  
  @RequestMapping(value={"student/comment-list/{commentType}/{referId}/{index}/{indexId}"}, method={org.springframework.web.bind.annotation.RequestMethod.GET})
  @ResponseBody
  public Message getQuestionComments(@PathVariable("commentType") int commentType, @PathVariable("referId") int referId, @PathVariable("index") int index, @PathVariable("indexId") int indexId)
  {
    if (index <= 0) {
      index = 1;
    }
    Message msg = new Message();
    msg.setMessageInfo("not-has-next");
    Page<Comment> page = new Page();
    if (index == 1)
    {
      page.setPageNo(index);
      page.setPageSize(6);
    }
    else
    {
      index += 2;
      page.setPageNo(index);
      page.setPageSize(2);
    }
    try
    {
      List<Comment> commentList = this.commentService.getCommentByTypeAndReferId(commentType, referId, indexId, page);
      Comments c = new Comments();
      c.setComments(commentList);
      c.setSize(page.getTotalRecord());
      if (page.getTotalRecord() > page.getPageSize() * index) {
        msg.setMessageInfo("has-next");
      }
      msg.setObject(c);
    }
    catch (Exception e)
    {
      msg.setResult(e.getClass().getName());
      e.printStackTrace();
    }
    return msg;
  }
  
  @RequestMapping(value={"student/submit-comment"}, method={org.springframework.web.bind.annotation.RequestMethod.POST})
  @ResponseBody
  public Message submitComment(@RequestBody Comment comment, HttpServletRequest request)
  {
    Message msg = new Message();
    UserInfo userInfo = (UserInfo)SecurityContextHolder.getContext().getAuthentication().getPrincipal();
    try
    {
      comment.setUserId(userInfo.getUserid());
      this.commentService.addComment(comment);
    }
    catch (Exception e)
    {
      e.printStackTrace();
      msg.setResult(e.getClass().getName());
    }
    return msg;
  }
}
